package com.xmall.aspect;

import cn.hutool.core.util.StrUtil;
import com.xmall.define.constants.CommonConstants;
import com.xmall.define.base.Result;
import com.xmall.define.base.ResultCode;
import com.xmall.define.constants.CommonProperties;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class RepeatSubmitAspect {

    @Resource
    private CommonProperties commonProperties;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Pointcut("@annotation(com.xmall.aspect.RepeatSubmit)")
    private void pointCut() {}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
        String token = "";
        if(null != RequestContextHolder.getRequestAttributes()){
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();

            // 重复提交 token
            token = request.getHeader(CommonConstants.RepeatSubmit.REQUEST_KEY);
            if(StrUtil.isBlank(token)){
                token = request.getParameter(CommonConstants.RepeatSubmit.REQUEST_KEY);
            }
            if(StrUtil.isBlank(token)){
                return Result.error(ResultCode.REPEAT_SUBMIT);
            }

            // 校验 token
            Boolean flag = redisTemplate.delete(CommonConstants.RepeatSubmit.REDIS_KEY + token);
            if(!flag) {
                return Result.error(ResultCode.REPEAT_SUBMIT);
            }
        }

        Object result;
        Object[] args = joinPoint.getArgs();
        try {
            result = joinPoint.proceed(args);
        } catch (Throwable throwable) {
            if(StrUtil.isNotBlank(token)){
                redisTemplate.opsForValue().set(CommonConstants.RepeatSubmit.REDIS_KEY + token, token, commonProperties.getRepeatSubmitTokenExpiredSeconds(), TimeUnit.SECONDS);
            }
            throw throwable;
        }

        return result;
    }
}
